package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.config.properties.CmnyProperties;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.mqtt.entity.MsgBodysenorHome;
import com.csun.cmny.provider.controller.websocket.WebSocketUtils;
import com.csun.cmny.provider.dao.DmcCsunGatewayLocationMapper;
import com.csun.cmny.provider.dao.DmcDeviceAlertMapper;
import com.csun.cmny.provider.device.csun.camera.entity.CsunCameraData;
import com.csun.cmny.provider.device.csun.sleep.SleepMessageHandler;
import com.csun.cmny.provider.device.csun.sleep.entity.CsunSleepData;
import com.csun.cmny.provider.exceptions.DmcBizException;
import com.csun.cmny.provider.model.constant.*;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.domain.DmcDeviceAlert;
import com.csun.cmny.provider.model.dto.DeviceAlertDto;
import com.csun.cmny.provider.model.dto.OldmanCheckStatDto;
import com.csun.cmny.provider.model.dto.alert.BatchHandleDeviceAlertDto;
import com.csun.cmny.provider.model.dto.alert.DeviceAlertPageQuery;
import com.csun.cmny.provider.model.dto.alert.HandleDeviceAlertDto;
import com.csun.cmny.provider.model.dto.alertConfig.AlertConfigQueryDto;
import com.csun.cmny.provider.model.dto.device.DeviceBindDto;
import com.csun.cmny.provider.model.dto.life.DeviceAlertLifeByIosSelectDto;
import com.csun.cmny.provider.model.enums.device.DeviceStatusEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceAlertTypeEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.*;
import com.csun.cmny.provider.model.vo.alertconfig.ConfigureOfflineAlertGroupVO;
import com.csun.cmny.provider.model.vo.csunbody.DmcCsunBodySensorVo;
import com.csun.cmny.provider.model.vo.csunbutton.DmcCsunButtonVo;
import com.csun.cmny.provider.model.vo.csuncamera.CsunCameraVo;
import com.csun.cmny.provider.model.vo.csundoor.DmcCsunDoorVo;
import com.csun.cmny.provider.model.vo.csunsleep.CsunSleepVo;
import com.csun.cmny.provider.model.vo.csunsleep.DmcCsunSleepVo;
import com.csun.cmny.provider.model.vo.device.DmcDeviceAlertLifeRoomVo;
import com.csun.cmny.provider.model.vo.device.DmcDeviceAlertLifeVo;
import com.csun.cmny.provider.model.vo.device.DmcDeviceAlertVo;
import com.csun.cmny.provider.model.vo.humidistat.CsunHumidistatVo;
import com.csun.cmny.provider.model.vo.life.DmcDeviceByRoom;
import com.csun.cmny.provider.model.vo.life.LifeTransducerConfigVO;
import com.csun.cmny.provider.model.vo.rfid.DmcRfidLabelVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.utils.DeviceUtils;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-02-25 13:27
 * @Description: the class dmc device alert service impl
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DmcDeviceAlertServiceImpl extends BaseService<DmcDeviceAlert>
        implements DmcDeviceAlertService {

    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private DeviceUtils deviceUtils;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private JPushService jpushService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private DmcDeviceAlertMapper dmcDeviceAlertMapper;
    @Resource
    private DmcCsunSleepBindService dmcCsunSleepBindService;
    @Resource
    private DmcCsunButtonLocationService dmcCsunButtonLocationService;
    @Resource
    private DmcCsunBodySensorLocationService dmcCsunBodySensorLocationService;
    @Resource
    private DmcCsunBodySensorConfigService dmcCsunBodySensorConfigService;
    @Resource
    private OmcRpcService omcRpcService;
    @Resource
    private UacRpcService uacRpcService;
    @Resource
    private WebSocketUtils webSocketUtils;
    @Resource
    private DmcCsunHumidistatLocationService dmcCsunHumidistatLocationService;
    @Resource
    private DmcCsunCameraLocationService dmcCsunCameraLocationService;
    @Resource
    private DmcLifeTransducerRoomConfigService dmcLifeTransducerRoomConfigService;
    @Resource
    private DmcConfigureOfflineAlertGroupService dmcConfigureOfflineAlertGroupService;
    @Resource
    private DmcDeviceOnlineRecordService dmcDeviceOnlineRecordService;
    @Resource
    private DmcCsunGatewayLocationService dmcCsunGatewayLocationService;
    @Resource
    private DmcCsunGatewayLocationMapper dmcCsunGatewayLocationMapper;
    @Resource
    private DmcDeviceUserBindService dmcDeviceUserBindService;
    @Resource
    private DmcCsunDoorLocationService dmcCsunDoorLocationService;
    @Resource
    private DmcCsunBodyGroupBindService dmcCsunBodyGroupBindService;
    @Resource
    private DmcCsunCameraAlertVideoService videoService;
    @Resource
    private CmnyProperties cmnyProperties;

    public static ConcurrentHashMap<Long, Set<String>> groupOfflineAlertConfigMap = new ConcurrentHashMap<>();

    /**
     * query device alert list with page
     *
     * @param deviceAlertPageQuery device alert page query
     * @return page info
     */
    @Override
    public PageInfo queryDeviceAlertListWithPage(DeviceAlertPageQuery deviceAlertPageQuery) {

        PageHelper.startPage(deviceAlertPageQuery.getPageNum(), deviceAlertPageQuery.getPageSize());


        List<DmcDeviceAlertVo> dmcDeviceAlertVoList = dmcDeviceAlertMapper
                .queryDeviceAlertListWithPage(deviceAlertPageQuery);

        return new PageInfo<>(dmcDeviceAlertVoList);
    }

    /**
     * delete device alert by id
     *
     * @param id id
     * @return the int.
     */
    @Override
    public Integer deleteDeviceAlertById(Long id) {

        Preconditions.checkArgument(id != null,
                cmnyMessageSource.getMessage("device.alert.id.null", null));

        DmcDeviceAlert dmcDeviceAlert = dmcDeviceAlertMapper.selectByPrimaryKey(id);
        Integer result = dmcDeviceAlertMapper.deleteByPrimaryKey(id);
        if (result > 1) {
            // 推送查询最近报警信息
            deleteDeviceAlertMsg(dmcDeviceAlert);
        }

        return result;
    }

    /**
     * batch delete by id list
     *
     * @param deleteIdList delete id list
     * @return the int.
     */
    @Override
    public Integer batchDeleteByIdList(List<Long> deleteIdList) {

        Preconditions.checkArgument(PublicUtil.isNotEmpty(deleteIdList),
                cmnyMessageSource.getMessage("device.alert.delete.id.list.null", null));

        return dmcDeviceAlertMapper.batchDeleteByIdList(deleteIdList);
    }

    /**
     * query device alert list by id list
     *
     * @param idList id list
     * @return the list.
     */
    @Override
    public List<DmcDeviceAlert> queryDeviceAlertListByIds(List<Long> idList) {

        return dmcDeviceAlertMapper.queryDeviceAlertListByIds(idList);
    }

    /**
     * read device alert by id
     *
     * @param id           id
     * @param loginAuthDto login auth dto
     * @return the int
     */
    @Override
    public Integer readDeviceAlertById(Long id, LoginAuthDto loginAuthDto) {

        Preconditions.checkArgument(id != null,
                cmnyMessageSource.getMessage("device.alert.id.null", null));

        DmcDeviceAlert dmcDeviceAlert = dmcDeviceAlertMapper.selectByPrimaryKey(id);
        if (PublicUtil.isEmpty(dmcDeviceAlert)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610043);
        }

        dmcDeviceAlert.setIsRead(true);
        dmcDeviceAlert.setUpdateInfo(loginAuthDto);
        Integer result = dmcDeviceAlertMapper.updateByPrimaryKeySelective(dmcDeviceAlert);

        if (result > 0) {
            deleteDeviceAlertMsg(dmcDeviceAlert);
        }

        return result;
    }

    /**
     * batch read by id list
     *
     * @param readIdList   read id list
     * @param loginAuthDto login auth dto
     * @return the int
     */
    @Override
    public Integer batchReadByIdList(List<Long> readIdList, LoginAuthDto loginAuthDto) {

        Preconditions.checkArgument(PublicUtil.isNotEmpty(readIdList),
                cmnyMessageSource.getMessage("device.alert.read.id.list.null", null));

        DmcDeviceAlert dmcDeviceAlert = new DmcDeviceAlert();
        dmcDeviceAlert.setIsRead(true);
        dmcDeviceAlert.setUpdateInfo(loginAuthDto);

        Map<String, Object> map = Maps.newHashMap();
        map.put("idList", readIdList);
        map.put("dmcDeviceAlert", dmcDeviceAlert);

        return dmcDeviceAlertMapper.batchReadByIdList(map);
    }

    /**
     * handle device alert
     *
     * @param handleDeviceAlertDto handle device alert dto
     * @param loginAuthDto         login auth dto
     * @return the int
     */
    @Override
    public Integer handleDeviceAlert(HandleDeviceAlertDto handleDeviceAlertDto, LoginAuthDto loginAuthDto) {

        Long id = handleDeviceAlertDto.getId();

        Preconditions.checkArgument(id != null,
                cmnyMessageSource.getMessage("device.alert.id.null", null));

        Preconditions.checkArgument(PublicUtil.isNotEmpty(handleDeviceAlertDto.getHandleStatus()),
                cmnyMessageSource.getMessage("device.alert.handle.status.null", null));

        Preconditions.checkArgument(PublicUtil.isNotEmpty(handleDeviceAlertDto.getHandleStatus() >= 0
                        && handleDeviceAlertDto.getHandleStatus() <= 2),
                cmnyMessageSource.getMessage("device.alert.handle.status.range", null));

        Preconditions.checkArgument(PublicUtil.isNotEmpty(handleDeviceAlertDto.getHandleRemark()),
                cmnyMessageSource.getMessage("device.alert.handle.remark.null", null));

        /**
         * @date 2019012016
         * @author chisj
         * @desc 修复bug #4407 不能重复处理报警
         */
        DmcDeviceAlert dmcDeviceAlertQuery = dmcDeviceAlertMapper.selectByPrimaryKey(id);
        if (dmcDeviceAlertQuery == null) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610043);
        }

        /**
         * @date 2019-12-17
         * @author chisj
         * @desc 修复bug #4407 不能重复已经处理完成的报警
         */
        if (dmcDeviceAlertQuery.getIsHandle()
                && dmcDeviceAlertQuery.getHandleStatus().equals(1)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610072);
        }

        DmcDeviceAlert dmcDeviceAlert = new DmcDeviceAlert();
        BeanUtils.copyProperties(handleDeviceAlertDto, dmcDeviceAlert);

        dmcDeviceAlert.setIsRead(true);
        dmcDeviceAlert.setIsHandle(true);
        dmcDeviceAlert.setUpdateInfo(loginAuthDto);

        return dmcDeviceAlertMapper.updateByPrimaryKeySelective(dmcDeviceAlert);
    }

    /**
     * csun sleep alert msg
     *
     * @param deviceNo device no
     */
    @Override
    public Integer csunSleepAlertMsg(String deviceNo, DmcDeviceAlert dmcDeviceAlert,
                                     OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo, String sleepFunc) {

        DmcCsunSleepVo dmcCsunSleepVo = dmcCsunSleepBindService.getCsunSleepBindByDeviceNo(deviceNo);
        if (PublicUtil.isEmpty(dmcCsunSleepVo)) {
            return 0;
        }
        if (PublicUtil.isEmpty(dmcCsunSleepVo.getBindType())) {
            return 0;
        }

        DeviceBindDto deviceBindDto = new DeviceBindDto();
        BeanUtils.copyProperties(dmcCsunSleepVo, deviceBindDto);
        OldmanBedRoomBuildingVo obrvo = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);

        //如果房间报警屏蔽就不产生报警
        if (PublicUtil.isNotEmpty(obrvo) && PublicUtil.isNotEmpty(obrvo.getRoomId())) {
            if (redisTemplate.hasKey(RedisKeyUtil.getDmcRoomAlertSilentTime(obrvo.getRoomId().longValue()))) {
                return 0;
            }
            // 判断life入住者状态
            if (getRoomOldmanCheckStat(obrvo.getRoomId())) {
                return 0;
            }
        }



        dmcDeviceAlert.setCreatedTime(new Date());
        dmcDeviceAlert.setDeviceNo(deviceNo);
        dmcDeviceAlert.setDeviceId(dmcCsunSleepVo.getId());
        dmcDeviceAlert.setOldmanId(dmcCsunSleepVo.getOldmanId());
        dmcDeviceAlert.setOldmanName(dmcCsunSleepVo.getOldmanName());
        dmcDeviceAlert.setLocation(dmcCsunSleepVo.getLocation());
        if (obrvo != null) {
            if (obrvo.getLocation() != null) {
                dmcDeviceAlert.setLocation(obrvo.getLocation());
            }
            if (obrvo.getOldmanName() != null) {
                dmcDeviceAlert.setOldmanName(obrvo.getOldmanName());
            }
            if (obrvo.getOldmanId() != null) {
                dmcDeviceAlert.setOldmanId(obrvo.getOldmanId());
            }
            dmcDeviceAlert.setNursingGroupId(obrvo.getNursingGroupId());
            BeanUtils.copyProperties(obrvo, oldmanBedRoomBuildingVo);
        }
        if (dmcDeviceAlert.getOldmanName() == null || dmcDeviceAlert.getOldmanName().equals("")) {
            dmcDeviceAlert.setOldmanName("老人");
        }
        if(dmcCsunSleepVo.getBindType().equals(DeviceConstant.DEVICE_BIND_TYPE_LIFE)){
            List<Integer> bedIds = omcRpcService.listBedByRoomId(dmcCsunSleepVo.getRoomId());
            if(bedIds != null && bedIds.size() > 0){
                OldmanBedRoomBuildingVo vo = (OldmanBedRoomBuildingVo)redisTemplate.opsForValue().get(RedisKeyUtil.getOmcBedId(bedIds.get(0)));
                dmcDeviceAlert.setOldmanName(vo.getOldmanName());
            }
        }
        String alertInfo = "";
        String code = "";
        if (dmcDeviceAlert.getOldmanName() == null) {
            dmcDeviceAlert.setOldmanName(" ");
        }
        Object params[] = {dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName()};
        Object param[] = {dmcDeviceAlert.getOldmanName()};
        switch (sleepFunc) {
            case CsunSleepConstant.ACTION_OVER:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_SLEEP_ACTION.getKey());
//                alertInfo = String.format("[%s][%s]翻身报警, 请前往处理!",
//                        dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
                /**
                 * @date    2020-08-13
                 * @author  chisj
                 * @desc    如果没有位置信息，不用显示位置的[]
                 */
                if (PublicUtil.isEmpty(dmcDeviceAlert.getLocation())){
                    code = "alert.message.csun.sleep.action.location";
                }else {
                    code = "alert.message.csun.sleep.action";
                }
                break;
            case CsunSleepConstant.OFF_LINE:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_SLEEP_OFF_LINE.getKey());
//                alertInfo = String.format(DateUtil.getDay() + "[%s][%s]离线报警, 请前往处理!",
//                        dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
                /**
                 * @date    2020-08-13
                 * @author  chisj
                 * @desc    如果没有位置信息，不用显示位置的[]
                 */
                if (PublicUtil.isEmpty(dmcDeviceAlert.getLocation())){
                    code = "alert.message.csun.sleep.off.location";
                }else {
                    code = "alert.message.csun.sleep.off";
                }
                break;
            case CsunSleepConstant.OFF_BED:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_SLEEP_OFF_BED.getKey());
//                alertInfo = String.format(DateUtil.getDay() + "[%s][%s]离床报警, 请前往处理!",
//                        dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
                /**
                 * @date    2020-08-13
                 * @author  chisj
                 * @desc    如果没有位置信息，不用显示位置的[]
                 */
                if (PublicUtil.isEmpty(dmcDeviceAlert.getLocation())){
                    code = "alert.message.csun.sleep.bed.location";
                }else {
                    code = "alert.message.csun.sleep.bed";
                }
                break;
            case CsunSleepConstant.BREATH_ALERT:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_SLEEP_BREATH_ALERT.getKey());
//                alertInfo = String.format(DateUtil.getDay() + "[%s][%s]呼吸心跳异常, 请前往处理!",
//                        dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
                if (PublicUtil.isEmpty(dmcDeviceAlert.getLocation())){
                    code = "alert.message.csun.sleep.app";
                }else {
                    code = "alert.message.csun.sleep.breath";
                }
                break;
            case CsunSleepConstant.HEARTBEAT_ALERT:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_SLEEP_HEARTBEAT_ALERT.getKey());
//                alertInfo = String.format(DateUtil.getDay() + "[%s][%s]心跳异常, 请前往处理!",
//                        dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
                /**
                 * @date    2020-08-13
                 * @author  chisj
                 * @desc    如果没有位置信息，不用显示位置的[]
                 */
                if (PublicUtil.isEmpty(dmcDeviceAlert.getLocation())){
                    code = "alert.message.csun.sleep.heartbeat.location";
                }else {
                    code = "alert.message.csun.sleep.heartbeat";
                }
                break;
            case CsunSleepConstant.LEAVE_ROOM:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_LEAVE_ROOM_ALERT.getKey());
//                alertInfo = String.format(DateUtil.getDay() + "[%s][%s]心跳异常, 请前往处理!",
//                        dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
                code = "alert.message.csun.leave.room";
                break;

            default:
                log.error("未识别的床垫功能码");
                break;
        }

        alertInfo = cmnyMessageSource.getMessage(code, params, dmcCsunSleepVo.getGroupId());


        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setGroupId(dmcCsunSleepVo.getGroupId());
        Integer result = dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);

        if (obrvo != null && obrvo.getOldmanId() != null) {
            //将报警记录同步到交班日志中
//            syncAlertMsgToShiftLog(dmcDeviceAlert);
        }

        return result;
    }

    /**
     * 摄像头报警
     *
     * @param deviceId       the device id
     * @param dmcDeviceAlert the device alert
     * @param obrvo          the oldman bed room building vo
     * @param msgType        the msg type
     * @return
     */
    @Override
    public Integer csunCameraAlertMsg(Long deviceId, DmcDeviceAlert dmcDeviceAlert,
                                      OldmanBedRoomBuildingVo obrvo, String msgType) {

        CsunCameraVo csunCameraVo =
                dmcCsunCameraLocationService.getCsunCameraByDeviceId(deviceId);
        if (PublicUtil.isEmpty(csunCameraVo)) {
            return 0;
        }
        if (PublicUtil.isEmpty(csunCameraVo.getBindType())) {
            return 0;
        }

        DeviceBindDto deviceBindDto = new DeviceBindDto();
        BeanUtils.copyProperties(csunCameraVo, deviceBindDto);
        RoomBuildingVo rbv = deviceUtils.getRoomBuildingVo(deviceBindDto);

        //如果房间报警屏蔽就不产生报警
        if (rbv != null && PublicUtil.isNotEmpty(rbv.getRoomId())) {
            if (redisTemplate.hasKey(RedisKeyUtil.getDmcRoomAlertSilentTime(rbv.getRoomId().longValue()))) {
                return 0;
            }
            // 判断life入住者状态
            if (getRoomOldmanCheckStat(rbv.getRoomId())) {
                return 0;
            }
        }

        dmcDeviceAlert.setDeviceNo(csunCameraVo.getDeviceNo());
        dmcDeviceAlert.setDeviceId(csunCameraVo.getId());
        dmcDeviceAlert.setLocation(csunCameraVo.getLocation());
        dmcDeviceAlert.setCreatedTime(new Date());
        if (PublicUtil.isNotEmpty(rbv) && PublicUtil.isNotEmpty(rbv.getLocation())) {
            dmcDeviceAlert.setLocation(rbv.getLocation());
            dmcDeviceAlert.setNursingGroupId(rbv.getNursingGroupId());
            BeanUtils.copyProperties(rbv, obrvo);
        }
        Object params[] = {dmcDeviceAlert.getLocation()};
        dmcDeviceAlert.setGroupId(csunCameraVo.getGroupId());
        String alertInfo = "";

        switch (msgType) {
            case CameraConstant.CSUN_CAMERA_FILL:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_CAMERA_FILL.getKey());
                alertInfo = cmnyMessageSource.getMessage("alert.message.csun.camera.fill",
                        params, csunCameraVo.getGroupId());
                dmcDeviceAlert.setAlertInfo(alertInfo);
                break;
            case CameraConstant.OFF_LINE:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_CAMERA_OFF_LINE.getKey());
                alertInfo = cmnyMessageSource.getMessage("alert.message.csun.camera.off",
                        params, csunCameraVo.getGroupId());
                dmcDeviceAlert.setAlertInfo(alertInfo);
                break;
        }

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    /**
     * device body group alert
     *
     * @param dmcCsunBodyGroup
     * @param dmcDeviceAlert
     * @param obrvo
     *
     * @return  the int.
     */
    @Override
    public Integer deviceBodyGroupAlert(DmcCsunBodyGroup dmcCsunBodyGroup, DmcDeviceAlert dmcDeviceAlert,
                                 OldmanBedRoomBuildingVo obrvo) {

        if (PublicUtil.isEmpty(dmcCsunBodyGroup)) {
            return 0;
        }

//        List<BodyGroupBindVo> bodyGroupBindVoList = dmcCsunBodyGroupBindService.queryListById(dmcCsunBodyGroup.getId());
//        if (PublicUtil.isNotEmpty(bodyGroupBindVoList)) {
//            dmcDeviceAlert.setDeviceId(bodyGroupBindVoList.get(0).getDeviceId());
//            dmcDeviceAlert.setDeviceNo(bodyGroupBindVoList.get(0).getDeviceNo());
//        }

        dmcDeviceAlert.setDeviceId(dmcCsunBodyGroup.getDeviceId());
        dmcDeviceAlert.setDeviceNo(dmcCsunBodyGroup.getDeviceNo());
        dmcDeviceAlert.setLocation(dmcCsunBodyGroup.getLocation());
        dmcDeviceAlert.setCreatedTime(new Date());
        dmcDeviceAlert.setOldmanId(dmcCsunBodyGroup.getOldmanId());
        dmcDeviceAlert.setOldmanName(dmcCsunBodyGroup.getOldmanName());
        dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_BODY_GROUP.getKey());
        Object params[] = {dmcDeviceAlert.getLocation()};
        String alertInfo = cmnyMessageSource.getMessage("alert.message.csun.body.group",
                params, dmcCsunBodyGroup.getGroupId());
        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setDeviceId(0l); // 必填
        dmcDeviceAlert.setGroupId(dmcCsunBodyGroup.getGroupId());

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    /**
     * save rfid reader alert msg
     *
     * @param dmcRfidLabelVo the dmc rfid label vo
     * @param dmcDeviceAlert the device alert
     * @param obrvo          the oldman bed room building vo
     * @return the int
     */
    @Override
    public Integer rfidReaderAlertMsg(String location, DmcRfidLabelVo dmcRfidLabelVo, DmcDeviceAlert dmcDeviceAlert,
                                      OldmanBedRoomBuildingVo obrvo) {

        dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.RFID_ALERT.getKey());
        dmcDeviceAlert.setDeviceNo(dmcRfidLabelVo.getDeviceNo());
        dmcDeviceAlert.setDeviceId(dmcRfidLabelVo.getId());
        dmcDeviceAlert.setOldmanId(dmcRfidLabelVo.getOldmanId().intValue());
        dmcDeviceAlert.setOldmanName(dmcRfidLabelVo.getOldmanName());
        dmcDeviceAlert.setLocation(location);
        dmcDeviceAlert.setOldmanName(obrvo.getOldmanName());
        dmcDeviceAlert.setOldmanId(obrvo.getOldmanId());
        dmcDeviceAlert.setNursingGroupId(obrvo.getNursingGroupId());
        dmcDeviceAlert.setCreatedTime(new Date());

//        String alertInfo = String.format("携带门禁卡的[%s]房间[%s]老人正通过[%s]离开, 请前往处理!",
//                obrvo.getLocation(), dmcDeviceAlert.getOldmanName(), location);
        Object params[] = {dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName(), location};
        String alertInfo = cmnyMessageSource.getMessage("alert.message.rfid.reader.error",
                params, dmcRfidLabelVo.getGroupId());
        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setGroupId(dmcRfidLabelVo.getGroupId());

        //将报警记录同步到交班日志中
//        syncAlertMsgToShiftLog(dmcDeviceAlert);

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    /**
     * save rfid reader group alert msg
     *
     * @param alarmLightVo   the alarm light vo
     * @param dmcRfidLabelVo the dmc rfid label vo
     * @param dmcDeviceAlert the device alert
     * @param obrvo          the oldman bed room building vo
     * @return the int.
     */
    @Override
    public Integer rfidReaderGroupAlertMsg(AlarmLightVo alarmLightVo, DmcRfidLabelVo dmcRfidLabelVo,
                                           DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo) {

        dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.ALARM_LIGHT.getKey());
        dmcDeviceAlert.setDeviceNo(alarmLightVo.getDeviceNo());
        dmcDeviceAlert.setDeviceId(alarmLightVo.getId());
        dmcDeviceAlert.setOldmanId(dmcRfidLabelVo.getOldmanId().intValue());
        dmcDeviceAlert.setOldmanName(dmcRfidLabelVo.getOldmanName());
        dmcDeviceAlert.setLocation(alarmLightVo.getLocation());
        dmcDeviceAlert.setOldmanName(obrvo.getOldmanName());
        dmcDeviceAlert.setOldmanId(obrvo.getOldmanId());
        dmcDeviceAlert.setNursingGroupId(obrvo.getNursingGroupId());
        dmcDeviceAlert.setCreatedTime(new Date());

        Object params[] = {obrvo.getLocation(), dmcDeviceAlert.getOldmanName(), DateUtil.dateToString(new Date()), alarmLightVo.getLocation()};
        String alertInfo = cmnyMessageSource.getMessage("alert.message.rfid.reader.group.error", params,
                dmcRfidLabelVo.getGroupId());
//        String alertInfo = String.format("[%s]房间的[%s]老人在%s经过[%s]位置的门禁二,该老人未被允许外出,请前往处理!",
//                obrvo.getLocation(), dmcDeviceAlert.getOldmanName(), DateUtil.dateToString(new Date()), alarmLightVo.getLocation());
        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setGroupId(dmcRfidLabelVo.getGroupId());

        //将报警记录同步到交班日志中
//        syncAlertMsgToShiftLog(dmcDeviceAlert);

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    @Override
    public Integer countAlertTimesByTypeAndTime(DeviceAlertPageQuery deviceAlertPageQuery) {
        return dmcDeviceAlertMapper.countAlertTimesByTypeAndTime(deviceAlertPageQuery);
    }

    /**
     * csun button alert msg
     *
     * @param deviceNo device no
     */
    @Override
    public Integer csunButtonAlertMsg(String deviceNo, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo) {

        DmcCsunButtonVo dmcCsunButtonVo = dmcCsunButtonLocationService.getCsunButtonByDeviceNo(deviceNo);
        if (PublicUtil.isEmpty(dmcCsunButtonVo)) {
            return 0;
        }
        if (PublicUtil.isEmpty(dmcCsunButtonVo.getBindType())) {
            return 0;
        }

        DeviceBindDto deviceBindDto = new DeviceBindDto();
        BeanUtils.copyProperties(dmcCsunButtonVo, deviceBindDto);
        OldmanBedRoomBuildingVo obrvo = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);

        //dmcDeviceAlert = new DmcDeviceAlert();
        dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_BUTTON.getKey());
        dmcDeviceAlert.setDeviceNo(deviceNo);
        dmcDeviceAlert.setDeviceId(dmcCsunButtonVo.getId());
        dmcDeviceAlert.setOldmanId(dmcCsunButtonVo.getOldmanId());
        dmcDeviceAlert.setOldmanName(dmcCsunButtonVo.getOldmanName());
        dmcDeviceAlert.setLocation(dmcCsunButtonVo.getLocation());
        dmcDeviceAlert.setCreatedTime(new Date());
        if (obrvo != null) {
            if (obrvo.getLocation() != null) {
                dmcDeviceAlert.setLocation(obrvo.getLocation());
            }
            if (obrvo.getOldmanName() != null) {
                dmcDeviceAlert.setOldmanName(obrvo.getOldmanName());
            }
            if (obrvo.getOldmanId() != null) {
                dmcDeviceAlert.setOldmanId(obrvo.getOldmanId());
            }
            dmcDeviceAlert.setNursingGroupId(obrvo.getNursingGroupId());
            BeanUtils.copyProperties(obrvo, oldmanBedRoomBuildingVo);
        }
//        String alertInfo = String.format("[%s]的[%s]使用紧急按钮进行了呼叫, 请前往处理!",
//                dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
        Object params[] = {dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName()};
        String alertInfo = cmnyMessageSource.getMessage("alert.message.csun.button", params,
                dmcCsunButtonVo.getGroupId());
        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setGroupId(dmcCsunButtonVo.getGroupId());

        //将报警记录同步到交班日志中
//        syncAlertMsgToShiftLog(dmcDeviceAlert);

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    @Override
    public Integer csunDoorAlertMsg(String deviceNo, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo) {

        DmcCsunDoorVo dmcCsunDoorVo = dmcCsunDoorLocationService.getCsunDoorByDeviceNo(deviceNo);
        if (PublicUtil.isEmpty(dmcCsunDoorVo)) {
            return 0;
        }
        if (PublicUtil.isEmpty(dmcCsunDoorVo.getBindType())) {
            return 0;
        }

        DeviceBindDto deviceBindDto = new DeviceBindDto();
        BeanUtils.copyProperties(dmcCsunDoorVo, deviceBindDto);
        OldmanBedRoomBuildingVo obrvo = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);

        //dmcDeviceAlert = new DmcDeviceAlert();
        dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_DOOR.getKey());
        dmcDeviceAlert.setDeviceNo(deviceNo);
        dmcDeviceAlert.setDeviceId(dmcCsunDoorVo.getId());
        dmcDeviceAlert.setOldmanId(dmcCsunDoorVo.getOldmanId());
        dmcDeviceAlert.setOldmanName(dmcCsunDoorVo.getOldmanName());
        dmcDeviceAlert.setLocation(dmcCsunDoorVo.getLocation());
        dmcDeviceAlert.setCreatedTime(new Date());
        if (obrvo != null) {
            if (obrvo.getLocation() != null) {
                dmcDeviceAlert.setLocation(obrvo.getLocation());
            }
            if (obrvo.getOldmanName() != null) {
                dmcDeviceAlert.setOldmanName(obrvo.getOldmanName());
            }
            if (obrvo.getOldmanId() != null) {
                dmcDeviceAlert.setOldmanId(obrvo.getOldmanId());
            }
            dmcDeviceAlert.setNursingGroupId(obrvo.getNursingGroupId());
            BeanUtils.copyProperties(obrvo, oldmanBedRoomBuildingVo);
        }
//        String alertInfo = String.format("[%s]的[%s]使用紧急按钮进行了呼叫, 请前往处理!",
//                dmcDeviceAlert.getLocation(), dmcDeviceAlert.getOldmanName());
        Object params[] = {dmcDeviceAlert.getLocation()};
        String alertInfo = cmnyMessageSource.getMessage("alert.message.csun.door", params,
                dmcCsunDoorVo.getGroupId());
        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setGroupId(dmcCsunDoorVo.getGroupId());

        //将报警记录同步到交班日志中
//        syncAlertMsgToShiftLog(dmcDeviceAlert);

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    @Override
    public Integer csunGatewayAlertMsg(String deviceNo, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo, String msgType) {

        DmcDevice dmcDevice = dmcDeviceService.queryDeviceByNumber(deviceNo);
        if (PublicUtil.isEmpty(dmcDevice)) {
            return 0;
        }
        if (dmcDevice.getDeviceType() != DeviceConstant.CSUN_GATEWAY) {
            return 0;
        }

        String alertInfo = "";

        Long id = dmcDevice.getId();
        switch (msgType) {
            case GatewayConstant.OFF_LINE:

                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_GATEWAY_OFF_LINE.getKey());

                DmcCsunGatewayLocation dmcCsunGatewayLocation = dmcCsunGatewayLocationMapper.selectByPrimaryKey(id);
                if (PublicUtil.isNotEmpty(dmcCsunGatewayLocation)) {

                    if (dmcCsunGatewayLocation.getRoomId() != null) {
//                        RoomBuildingVo roomBuildingVo = omcRpcService.queryRoomBuildingByRoomId(dmcCsunGatewayLocation.getRoomId());
//                        Object params[] = {dmcDevice.getDeviceNo(), roomBuildingVo.getRoomNo()};
                        DeviceBindDto deviceBindDto = new DeviceBindDto();
                        deviceBindDto.setBindType(dmcCsunGatewayLocation.getBindType());
                        deviceBindDto.setRoomId(dmcCsunGatewayLocation.getRoomId());
                        RoomBuildingVo redisVo = deviceUtils.getRoomBuildingVo(deviceBindDto);
                        dmcDeviceAlert.setLocation(redisVo.getRoomNo());
                        dmcDeviceAlert.setNursingGroupId(redisVo.getNursingGroupId());
                    }
                    if (dmcCsunGatewayLocation.getLocation() == null) {
                        dmcCsunGatewayLocation.setLocation(" ");
                    }
                    Object params[] = {dmcDevice.getDeviceNo(), dmcCsunGatewayLocation.getLocation()};

                    //网关报警位置默认置为房间号
                    if(PublicUtil.isEmpty(dmcDeviceAlert.getLocation())){
                        dmcDeviceAlert.setLocation(dmcCsunGatewayLocation.getLocation());
                    }

                    alertInfo = cmnyMessageSource.getMessage("alert.message.csun.gateway.off", params, dmcDevice.getGroupId());
                    dmcDeviceAlert.setDeviceNo(deviceNo);
                    dmcDeviceAlert.setDeviceId(dmcDevice.getId());
                    dmcDeviceAlert.setCreatedTime(new Date());

                    dmcDeviceAlert.setAlertInfo(alertInfo);
                    dmcDeviceAlert.setGroupId(dmcDevice.getGroupId());

                    return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
                }
                break;
            default:
                log.info("unknow gateway alert type");
                return 0;
        }

        return 0;
    }

    /**
     * csun body sensor alert msg
     *
     * @param deviceNo device no
     * @param level
     */
    @Override
    public Integer csunBodySensorAlertMsg(String deviceNo, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo, Integer level) {

        DmcCsunBodySensorVo dmcCsunBodySensorVo =
                dmcCsunBodySensorLocationService.getCsunBodySensorByDeviceNo(deviceNo);
        if (PublicUtil.isEmpty(dmcCsunBodySensorVo)) {
            return 0;
        }
        if (PublicUtil.isEmpty(dmcCsunBodySensorVo.getBindType())) {
            return 0;
        }

        // 判断设备类型
        if (!dmcCsunBodySensorVo.getDeviceType().equals(6) &&
                !dmcCsunBodySensorVo.getDeviceType().equals(16)) {
            log.warn("the device [{}] not body sensor...", dmcCsunBodySensorVo.getDeviceNo());
            return 0;
        }

        DeviceBindDto deviceBindDto = new DeviceBindDto();
        BeanUtils.copyProperties(dmcCsunBodySensorVo, deviceBindDto);
        RoomBuildingVo rbv = deviceUtils.getRoomBuildingVo(deviceBindDto);

        // RoomBuildingVo rbv = omcRpcService.queryRoomBuildingByRoomId(dmcCsunBodySensorVo.getRoomId());
        dmcDeviceAlert.setDeviceNo(deviceNo);
        dmcDeviceAlert.setDeviceId(dmcCsunBodySensorVo.getId());
        dmcDeviceAlert.setLocation(dmcCsunBodySensorVo.getLocation());
        dmcDeviceAlert.setCreatedTime(new Date());
        dmcDeviceAlert.setGroupId(dmcCsunBodySensorVo.getGroupId());

        if (PublicUtil.isNotEmpty(rbv) && PublicUtil.isNotEmpty(rbv.getLocation())) {
            dmcDeviceAlert.setLocation(rbv.getLocation());
            dmcDeviceAlert.setNursingGroupId(rbv.getNursingGroupId());
            BeanUtils.copyProperties(rbv, obrvo);
        }

        String code = "";
//        if (dmcCsunBodySensorVo.getBindType().equals(DeviceConstant.DEVICE_BIND_TYPE_LIFE) || level != null) {

        //如果房间报警屏蔽就不产生报警
        if (PublicUtil.isNotEmpty(dmcCsunBodySensorVo.getRoomId())) {
            if (redisTemplate.hasKey(RedisKeyUtil.getDmcRoomAlertSilentTime(dmcCsunBodySensorVo.getRoomId().longValue()))) {
                return 0;
            }
            // 判断life入住者状态
            if (getRoomOldmanCheckStat(dmcCsunBodySensorVo.getRoomId())) {
                return 0;
            }
        }

        switch (level) {
            case LifeConstant.BODY_SENSOR_TOILET_ATTENTION_LEVEL:
                    dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_LIFE_BODY_SENSOR_ALERT_LEVEL_ONE.getKey());
                    code = "alert.message.csun.body.sensor.throw.one";
                //dmcDeviceAlert.setAlertInfo(dmcCsunBodySensorVo.getLocation()+":"+DmcDeviceAlertTypeEnum.CSUN_LIFE_BODY_SENSOR_ALERT_LEVEL_ONE.getValue());
                break;
            case LifeConstant.BODY_SENSOR_TOILET_WARNING_LEVEL:
                    dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_LIFE_BODY_SENSOR_ALERT_LEVEL_TWO.getKey());
//                    dmcDeviceAlert.setAlertInfo(dmcCsunBodySensorVo.getLocation() +":"+ DmcDeviceAlertTypeEnum.CSUN_LIFE_BODY_SENSOR_ALERT_LEVEL_TWO.getValue());
                    code = "alert.message.csun.body.sensor.throw.two";
                break;
            case LifeConstant.BODY_SENSOR_TOILET_UNUSUAL_LEVEL:
                    dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_LIFE_BODY_SENSOR_ALERT_LEVEL_THREE.getKey());
//                    dmcDeviceAlert.setAlertInfo(dmcCsunBodySensorVo.getLocation() +":"+ DmcDeviceAlertTypeEnum.CSUN_LIFE_BODY_SENSOR_ALERT_LEVEL_THREE.getValue());
                    code = "alert.message.csun.body.sensor.throw.three";
                break;
            case BodySensorConstant.OFF_LINE:
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_BODYSENSOR_OFF_LINE.getKey());
                code = "alert.message.csun.body.sensor.off";
                break;
            default:
                throw new DmcBizException(ErrorCodeEnum.DMC100613002);
        }

        Object params[] = {dmcDeviceAlert.getLocation()};
        String alertInfo = cmnyMessageSource.getMessage(code, params,
                dmcCsunBodySensorVo.getGroupId());
        log.info("====> chisj alert info = {}", alertInfo);
        dmcDeviceAlert.setAlertInfo(alertInfo);
//        } else {
//            //DmcDeviceAlert dmcDeviceAlert = new DmcDeviceAlert();
//            dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_BODY_SENSOR.getKey());
//            dmcDeviceAlert.setAlertInfo(DmcDeviceAlertTypeEnum.CSUN_BODY_SENSOR.getValue());
//
////            String alertInfo = String.format("[%s]的人体感应出现异常, 请前往处理!",
////                    dmcDeviceAlert.getLocation());
//            Object params[] = {dmcDeviceAlert.getLocation()};
//            String alertInfo = cmnyMessageSource.getMessage("alert.message.csun.body.sensor.error", params,
//                    dmcCsunBodySensorVo.getGroupId());
//            dmcDeviceAlert.setAlertInfo(alertInfo);
//
//            //将报警记录同步到交班日志中
//            syncAlertMsgToShiftLog(dmcDeviceAlert);
//        }
        /**
         * @Auther: ZNR
         * @Date: 2021-01-13
         * 当人感报警时，只有对应开关启用，报警信息才会存入数据库
         */
        DmcCsunBodySensorConfig config = dmcCsunBodySensorConfigService.selectByKey(dmcDeviceAlert.getDeviceId());
        if ((level==LifeConstant.BODY_SENSOR_TOILET_ATTENTION_LEVEL && config.getIsUseToiletAttentionTime()==0)||
                (level==LifeConstant.BODY_SENSOR_TOILET_WARNING_LEVEL && config.getIsUseToiletWarningTime()==0)||
                (level==LifeConstant.BODY_SENSOR_TOILET_UNUSUAL_LEVEL && config.getIsUseToiletUnusualTime()==0)){
            return 0;
        }else {
            return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
        }

    }

    /**
     * 孝心手环报警
     *
     * @param dmcDeviceAlert the dmc device alert
     * @param obrvo          the oldman bed room building vo
     * @return the int.
     */
    @Override
    public Integer watchAlertMsg(DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo) {

        dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.WX_WATCH.getKey());
        dmcDeviceAlert.setCreatedTime(new Date());
        dmcDeviceAlert.setNursingGroupId(obrvo.getNursingGroupId());

        //将报警记录同步到交班日志中
//        syncAlertMsgToShiftLog(dmcDeviceAlert);

        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    /**
     * 温度异常报警
     *
     * @param deviceNo       温度传感器编号
     * @param dmcDeviceAlert 报警信息
     * @param obrvo          楼栋楼层信息
     * @return the int.
     */
    @Override
    public Integer csunHumidistatAlertMsg(String deviceNo, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo, String msgType) {

        CsunHumidistatVo csunHumidistatVo = dmcCsunHumidistatLocationService.getCsunHumidistatByDeviceNo(deviceNo);

        if (PublicUtil.isEmpty(csunHumidistatVo)) { // 温度传感器设备不存在
            return 0;
        }

        if (PublicUtil.isEmpty(csunHumidistatVo.getBindType())) {   // 温度传感器尚未绑定
            return 0;
        }

        // 判断绑定方式
        DeviceBindDto deviceBindDto = new DeviceBindDto();
        BeanUtils.copyProperties(csunHumidistatVo, deviceBindDto);
        RoomBuildingVo rbv = deviceUtils.getRoomBuildingVo(deviceBindDto);

        Object[] params =null;

        //如果房间报警屏蔽就不产生报警
        if (PublicUtil.isNotEmpty(rbv)){
            if (PublicUtil.isNotEmpty(rbv.getRoomId())) {
                if (redisTemplate.hasKey(RedisKeyUtil.getDmcRoomAlertSilentTime(rbv.getRoomId().longValue()))) {
                    return 0;
                }
                // 判断life入住者状态
                if (getRoomOldmanCheckStat(rbv.getRoomId())) {
                    return 0;
                }
            }

             params= new Object[]{rbv.getLocation()};
        }
        //如果是自定义绑定,就查一下自定义绑定的位置
        if (deviceBindDto.getBindType().equals(0)){

            DmcCsunHumidistatLocation dmcCsunHumidistatLocation = dmcCsunHumidistatLocationService.selectlocationBydeviceNo(deviceNo);

            params=new Object[]{dmcCsunHumidistatLocation.getLocation()};

        }


        String alertInfo = "";
//        Object params[] = {dmcDeviceAlert.getLocation()};

        switch (msgType) {
            case HumidistatConstant.CSUN_TEMPERATURE_ANOMAL:
                alertInfo = cmnyMessageSource.getMessage("alert.message.csun.humidistat.error", params,
                        csunHumidistatVo.getGroupId());
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_HUMIDISTAT_ERROR.getKey());
                break;
            case HumidistatConstant.OFF_LINE:
                alertInfo = cmnyMessageSource.getMessage("alert.message.csun.humidistat.off", params,
                        csunHumidistatVo.getGroupId());
                dmcDeviceAlert.setAlertType(DmcDeviceAlertTypeEnum.CSUN_HUMIDISTAT_OFF_LINE.getKey());
                break;
        }


        dmcDeviceAlert.setDeviceNo(deviceNo);
        dmcDeviceAlert.setDeviceId(csunHumidistatVo.getId());
        dmcDeviceAlert.setLocation(csunHumidistatVo.getLocation());
        dmcDeviceAlert.setCreatedTime(new Date());

        if (PublicUtil.isNotEmpty(rbv) && PublicUtil.isNotEmpty(rbv.getLocation())) {
            dmcDeviceAlert.setLocation(rbv.getLocation());
            dmcDeviceAlert.setNursingGroupId(rbv.getNursingGroupId());
            dmcDeviceAlert.setOldmanId(rbv.getOldmanId());
            dmcDeviceAlert.setOldmanName(rbv.getOldmanName());
            BeanUtils.copyProperties(rbv, obrvo);
        }

        dmcDeviceAlert.setAlertInfo(alertInfo);
        dmcDeviceAlert.setGroupId(csunHumidistatVo.getGroupId());


        return dmcDeviceAlertMapper.insertSelective(dmcDeviceAlert);
    }

    /**
     * query device alert by building id and floor no
     *
     * @param deviceReqVoList device req vo list
     * @return
     */
    @Override
    public List<DmcDeviceAlertVo> queryDeviceAlertByBuildingIdAndFloorNo(List<DeviceReqVo> deviceReqVoList) {

        return dmcDeviceAlertMapper.queryDeviceAlertByBuildingIdAndFloorNo(deviceReqVoList);
    }

    /**
     * update device alert play times by id
     *
     * @param id device alert id
     * @return the int.
     */
    @Override
    public Integer updateDeviceAlertPlayTimesById(Long id) {

        return dmcDeviceAlertMapper.updateDeviceAlertPlayTimesById(id);
    }

    public void sendLifeMsg(DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo, String sound) {

        String message = JSONObject.fromObject(dmcDeviceAlert).toString();

        List<String> tagList = Lists.newArrayList();
        tagList.add(cmnyProperties.getJpush().getPrefix() + DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId());

        jpushService.sendLifeMsg(cmnyMessageSource.getMessage("device.alert.msg.send", null),
                cmnyMessageSource.getMessage("device.alert.msg.query", null),
                dmcDeviceAlert.getAlertInfo(),
                message,
                tagList,
                sound);
    }

    public void sendDeviceAlertMsg(DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo) {

        String message = JSONObject.fromObject(dmcDeviceAlert).toString();

        try {
            // WebSocketServer.sendMessage(message, dmcDeviceAlert.getGroupId() + "");
            webSocketUtils.pushWebsocketMessageWithAlert(dmcDeviceAlert);
        } catch (Exception e) {
            log.error("web socket send message error ====> ", e.getMessage());
        }

        List<String> tagList = Lists.newArrayList();
        tagList.add(DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId());
        /**
         * @data 2019-09-12
         * @author chisj
         * @desc 推送给班组
         */
        Long nursingGroupId = dmcDeviceAlert.getNursingGroupId();
        if (nursingGroupId != null) {
            tagList.add(DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId() + "_" + DmcConstant.NURSING_PREFIX + nursingGroupId);
        }
        if (oldmanBedRoomBuildingVo != null) {
            tagList.add(DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId()
                    + "_" + oldmanBedRoomBuildingVo.getBuildingId()
                    + "_" + oldmanBedRoomBuildingVo.getFloorNo());
        }

        // 楼栋楼层刷新 -- 暂时未整改未JPush重构
        jpushService.sendBuildingFloorUpdateMsg(tagList);

        /**
         * @data 2020-04-10
         * @author chisj
         * @desc 给个人推送报警
         */
        List<String> tagListOneProper = Lists.newArrayList();
        DmcDeviceUserBind record = new DmcDeviceUserBind();
        record.setDeviceId(dmcDeviceAlert.getDeviceId());
        List<DmcDeviceUserBind> userBindList = dmcDeviceUserBindService.select(record);
        if (PublicUtil.isNotEmpty(userBindList)) {
            for (DmcDeviceUserBind user : userBindList) {
                tagList.add(DmcConstant.USER_PREFIX + user.getUserId());
//                tagListOneProper.add(DmcConstant.USER_PREFIX + user.getUserId());
            }
        }


        // 报警推送 -- 暂时未整改未JPush重构
        jpushService.sendToAll(cmnyMessageSource.getMessage("device.alert.msg.send", null),
                cmnyMessageSource.getMessage("device.alert.msg.query", null),
                dmcDeviceAlert.getAlertInfo(),
                message,
                tagList);
        //报警推送给个人
//        jpushService.sendToAll(cmnyMessageSource.getMessage("device.alert.msg.send", null),
//                cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                dmcDeviceAlert.getAlertInfo(),
//                message,
//                tagListOneProper);
    }

    public void deleteDeviceAlertMsg(DmcDeviceAlert dmcDeviceAlert) {

        log.info("====> chisj delete device alert msg ... {}", dmcDeviceAlert.toString());
        OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo = null;
        if (PublicUtil.isNotEmpty(dmcDeviceAlert)) {
            // 判断报警类型
            if (dmcDeviceAlert.getAlertType().equals(DmcDeviceAlertTypeEnum.ALARM_LIGHT.getKey())) {
                // 报警灯
                oldmanBedRoomBuildingVo = omcRpcService
                        .queryOldmanBedRoomBuildingByOldmanId(dmcDeviceAlert.getOldmanId());
            } else {
                // 根据报警信息查询老人楼栋楼层
                DeviceBindDto deviceBindDto = dmcDeviceService.getDeviceBindDto(dmcDeviceAlert);
                if (PublicUtil.isNotEmpty(deviceBindDto)) {
                    if (dmcDeviceAlert.getAlertType() == 3) {
                        RoomBuildingVo rbv = deviceUtils.getRoomBuildingVo(deviceBindDto);
                        if (PublicUtil.isEmpty(rbv)) {
                            return;
                        }
                        oldmanBedRoomBuildingVo = new OldmanBedRoomBuildingVo();
                        BeanUtils.copyProperties(rbv, oldmanBedRoomBuildingVo);
                    } else {
                        oldmanBedRoomBuildingVo = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);
                        if (PublicUtil.isEmpty(oldmanBedRoomBuildingVo)) {
                            return;
                        }
                    }
                }
            }
        }

        //String message = JSONObject.fromObject(dmcDeviceAlert).toString();
        try {
            // WebSocketServer.sendMessage(message, dmcDeviceAlert.getGroupId() + "");
            log.info("====> chisj push web socket message with alert ... {}");
            webSocketUtils.pushWebsocketMessageWithAlert(dmcDeviceAlert);
        } catch (Exception e) {
            log.error("web socket send message error ====> ", e.getMessage());
        }

        List<String> tagList = Lists.newArrayList();
        tagList.add(cmnyProperties.getJpush().getPrefix() + DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId());
        if (oldmanBedRoomBuildingVo != null) {
            tagList.add(DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId()
                    + "_" + oldmanBedRoomBuildingVo.getBuildingId()
                    + "_" + oldmanBedRoomBuildingVo.getFloorNo());
        }

//        jpushService.sendToAll(cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                message,
//                tagList);

        jpushService.sendBuildingFloorUpdateMsg(tagList);

        String message = JSONObject.fromObject(dmcDeviceAlert).toString();
        jpushService.sendLifeMsg(cmnyMessageSource.getMessage("device.alert.msg.query", null),
                cmnyMessageSource.getMessage("device.alert.msg.query", null),
                cmnyMessageSource.getMessage("device.alert.msg.query", null),
                message,
                tagList,
                LifeConstant.NO_SOUND);

    }

    public void deleteDeviceAlertListMsg(List<DmcDeviceAlert> dmcDeviceAlertList) {

        if (PublicUtil.isEmpty(dmcDeviceAlertList)) {
            return;
        }

        List<DmcDeviceAlert> distinctList = dmcDeviceAlertList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(o -> o.getDeviceId()))), ArrayList::new)
                );

        // String message = JSONObject.fromObject(dmcDeviceAlertList.get(0)).toString();
        try {
            // WebSocketServer.sendMessage(message, dmcDeviceAlert.getGroupId() + "");
            log.info("====> chisj push web socket message with batch alert ... {}");
            webSocketUtils.pushWebsocketMessageWithAlert(dmcDeviceAlertList.get(0));
        } catch (Exception e) {
            log.error("web socket send message error ====> ", e.getMessage());
        }

        Map<String, DmcDeviceAlert> tagMap = Maps.newHashMap();
        for (DmcDeviceAlert dmcDeviceAlert : distinctList) {
            tagMap.put(DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId(), dmcDeviceAlert);
            DeviceBindDto deviceBindDto = dmcDeviceService.getDeviceBindDto(dmcDeviceAlert);
            if (PublicUtil.isNotEmpty(deviceBindDto)) {
                OldmanBedRoomBuildingVo obrbv = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);
                if (PublicUtil.isEmpty(obrbv)) {
                    continue;
                }
                tagMap.put(DmcConstant.GROUP_PREFIX + dmcDeviceAlert.getGroupId()
                        + "_" + obrbv.getBuildingId()
                        + "_" + obrbv.getFloorNo(), dmcDeviceAlert);
            }
        }
        List<String> tagList = tagMap.keySet().stream().collect(Collectors.toList());

//        jpushService.sendToAll(cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                JSONObject.fromObject(new DmcDeviceAlert()).toString(),
//                tagList);
        jpushService.sendBuildingFloorUpdateMsg(tagList);
    }

    public void deleteByDeviceId(Long deviceId) {
        DmcDeviceAlert dmcDeviceAlertQuery = new DmcDeviceAlert();
        dmcDeviceAlertQuery.setDeviceId(deviceId);
        List<DmcDeviceAlert> dmcDeviceAlertList = dmcDeviceAlertMapper.select(dmcDeviceAlertQuery);
        // 4.删除报警信息
        if (PublicUtil.isNotEmpty(dmcDeviceAlertList)) {
            dmcDeviceAlertMapper.delete(dmcDeviceAlertQuery);
            // 5.推送
            deleteDeviceAlertListMsg(dmcDeviceAlertList);
        }
    }

    /**
     * query device alert by device list
     *
     * @param deviceReqVoList device req vo list
     * @return the list
     */
    @Override
    public List<DeviceAlertReqVo> queryDeviceAlertByDeviceList(List<DeviceReqVo> deviceReqVoList) {

        return dmcDeviceAlertMapper.queryDeviceAlertByDeviceList(deviceReqVoList);
    }

    /**
     * send sleep data by device id
     *
     * @param deviceId device id
     */
    @Override
    public void sendSleepDataByDeviceId(Long deviceId) {

        DeviceBindDto deviceBindDto = dmcDeviceService.getDeviceBindDtoByDeviceId(deviceId);
        if (PublicUtil.isEmpty(deviceBindDto)) {
            return;
        }
        OldmanBedRoomBuildingVo obrvo = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);
        if (PublicUtil.isEmpty(obrvo)) {
            return;
        }
        List<String> tagList = Lists.newArrayList();
        tagList.add(DmcConstant.GROUP_PREFIX + obrvo.getHomeId());
        tagList.add(DmcConstant.GROUP_PREFIX + obrvo.getHomeId()
                + "_" + obrvo.getBuildingId()
                + "_" + obrvo.getFloorNo());

//        jpushService.sendToAll(cmnyMessageSource.getMessage("device.alert.msg.send", null),
//                cmnyMessageSource.getMessage("device.alert.msg.query", null),
//                dmcDeviceAlert.getAlertInfo(),
//                message,
//                tagList);

        jpushService.sendBuildingFloorUpdateMsg(tagList);
    }

    /**
     * 批量处理报警信息
     *
     * @param batchHandleDeviceAlertDto
     * @param loginAuthDto
     * @return the int.
     */
    @Override
    public Integer batchHandleByIdList(BatchHandleDeviceAlertDto batchHandleDeviceAlertDto, LoginAuthDto loginAuthDto) {

        Preconditions.checkArgument(batchHandleDeviceAlertDto.getIdList() != null,
                cmnyMessageSource.getMessage("device.alert.id.list.null", null));

        Preconditions.checkArgument(batchHandleDeviceAlertDto.getIdList().size() > 0,
                cmnyMessageSource.getMessage("device.alert.id.list.null", null));

        Preconditions.checkArgument(PublicUtil.isNotEmpty(batchHandleDeviceAlertDto.getHandleStatus()),
                cmnyMessageSource.getMessage("device.alert.handle.status.null", null));

        Preconditions.checkArgument(PublicUtil.isNotEmpty(batchHandleDeviceAlertDto.getHandleStatus() >= 0
                        && batchHandleDeviceAlertDto.getHandleStatus() <= 2),
                cmnyMessageSource.getMessage("device.alert.handle.status.range", null));

        Preconditions.checkArgument(PublicUtil.isNotEmpty(batchHandleDeviceAlertDto.getHandleRemark()),
                cmnyMessageSource.getMessage("device.alert.handle.remark.null", null));

        DmcDeviceAlert dmcDeviceAlert = new DmcDeviceAlert();
        BeanUtils.copyProperties(batchHandleDeviceAlertDto, dmcDeviceAlert);

        dmcDeviceAlert.setIsRead(true);
        dmcDeviceAlert.setIsHandle(true);
        dmcDeviceAlert.setUpdateInfo(loginAuthDto);

        return dmcDeviceAlertMapper.batchUpdate(batchHandleDeviceAlertDto.getIdList(), dmcDeviceAlert);
    }

    @Override
    public List<DeviceAlertReqVo> queryDeviceAlertByOldIdAndDate(DeviceAlertReqVo deviceAlertReqVo) {

        //获取老人id集合
        List<Integer> oldmanIdList = deviceAlertReqVo.getOldmanIdList();

        //查询结果集
        List<DeviceAlertReqVo> deviceAlertReqVoList = new LinkedList<>();

        //循环查询
        for (Integer oldmanId : oldmanIdList) {

            //按oldmanId,creatTime查询
            deviceAlertReqVo.setOldmanId(oldmanId);
            List<DeviceAlertReqVo> temp = dmcDeviceAlertMapper.queryDeviceAlertByOldIdAndDate(deviceAlertReqVo);

            //插入结果集
            for (DeviceAlertReqVo item : temp) {
                deviceAlertReqVoList.add(item);
            }
        }
        return deviceAlertReqVoList;
    }

    @Override
    public Integer syncAlertMsgToShiftLog(DmcDeviceAlert dmcDeviceAlert) {
        DeviceAlertDto dto = new DeviceAlertDto();
        BeanUtils.copyProperties(dmcDeviceAlert, dto);
        return omcRpcService.syncAlertMsgToShiftLog(dto);
    }

    @Override
    public List<DmcDeviceAlertVo> queryDeviceAlertByOldId(Integer oldmanId) {
        return dmcDeviceAlertMapper.queryDeviceAlertByOldId(oldmanId);
    }


    @Override
    public List<DmcDeviceAlertLifeVo> queryDeviceAlertLife(Long groupId) {
        /**
         * @Auther: ZNR
         * @Date: 2021-01-12
         * 当人感报警时，只有对应开关启用，报警信息才会存入返回结果集
         */
        /*
        List<DmcDeviceAlertLifeVo> dmcDeviceAlertLifeVoList = dmcDeviceAlertMapper.queryDeviceAlertLife(groupId);
        List<DmcDeviceAlertLifeVo> dmcDeviceAlertLifeVos = new ArrayList<>();
        for (int i = 0 ; i < dmcDeviceAlertLifeVoList.size() ; i ++){
            DmcCsunBodySensorConfig config = dmcCsunBodySensorConfigService.selectByKey(dmcDeviceAlertLifeVoList.get(i).getDeviceId());
            if ((dmcDeviceAlertLifeVoList.get(i).getAlertType()==14 && config.getIsUseToiletAttentionTime()==0) ||
                    (dmcDeviceAlertLifeVoList.get(i).getAlertType()==15 && config.getIsUseToiletWarningTime()==0) ||
                    (dmcDeviceAlertLifeVoList.get(i).getAlertType()==16 && config.getIsUseToiletUnusualTime()==0)){
                continue;
            }else {
                dmcDeviceAlertLifeVos.add(dmcDeviceAlertLifeVoList.get(i));
            }
        }*/

        List<DmcDeviceAlertLifeVo> dmcDeviceAlertLifeVos = dmcDeviceAlertMapper.queryDeviceAlertLife(groupId);
        return dmcDeviceAlertLifeVos;
    }

    @Override
    public List<DmcDeviceAlertLifeRoomVo> queryDeviceAlertLifeRoom(List<Long> deviceIds, Long groupId) {
        return dmcDeviceAlertMapper.queryDeviceAlertLifeRoom(deviceIds, groupId);
    }


    @Override
    public Integer updateAlert(Long alertId, String loginName) {
        return dmcDeviceAlertMapper.updateAlert(alertId, loginName, new Date());
    }

    @Override
    public List<DmcDeviceAlertLifeRoomVo> selectAlertDataByRoomId(Long id, Long groupId) {

        List<Long> deviceIds = new ArrayList<>();

        List<DmcDeviceByRoom> dmcDeviceByRooms = dmcDeviceService.selectDeviceByRoomId(id, groupId);
        for (DmcDeviceByRoom dmcDeviceByRoom : dmcDeviceByRooms) {
            deviceIds.add(dmcDeviceByRoom.getDeviceId());
        }
        if (deviceIds != null && deviceIds.size() > 0) {
            return dmcDeviceAlertMapper.queryDeviceAlertLifeRoom(deviceIds, groupId);
        }

        return null;
    }

    @Override
    public List<DmcDeviceAlertLifeRoomVo> queryDeviceAlertLifeRoomAndTime(List<Long> deviceIds, Long groupId, Date startTime, Date endTime) {
        return dmcDeviceAlertMapper.queryDeviceAlertLifeRoomAndTime(deviceIds, groupId, startTime, endTime);
    }

    @Override
    public List<DmcDeviceAlertLifeVo> selectColor(List<Long> alertIds, Long groupId) {
        return dmcDeviceAlertMapper.selectColor(alertIds, groupId);
    }

    @Override
    public PageInfo queryDeviceAlertLifeRoomIndex(DeviceAlertPageQuery deviceAlertPageQuery) {

        List<Long> deviceIds = new ArrayList<>();

        List<DmcDeviceByRoom> dmcDeviceByRooms = dmcDeviceService.selectDeviceByRoomId(deviceAlertPageQuery.getRoomId(), deviceAlertPageQuery.getGroupId());
        for (DmcDeviceByRoom dmcDeviceByRoom : dmcDeviceByRooms) {
            deviceIds.add(dmcDeviceByRoom.getDeviceId());
        }

        //获取该房间的所有设备id
        deviceAlertPageQuery.setDeviceIds(deviceIds);

        if (PublicUtil.isNotEmpty(deviceIds)) {
            List<DmcDeviceAlertLifeRoomVo> dmcDeviceAlertLifeRoomVos = dmcDeviceAlertMapper.queryDeviceAlertLifeRoomIndex(deviceAlertPageQuery);
            //处理返回的报警信息
            if (PublicUtil.isNotEmpty(dmcDeviceAlertLifeRoomVos)) {

                for (DmcDeviceAlertLifeRoomVo dmcDeviceAlertLifeRoomVo : dmcDeviceAlertLifeRoomVos) {
                    if (dmcDeviceAlertLifeRoomVo.getIsHandle() == 0) {
                        dmcDeviceAlertLifeRoomVo.setUpdateTime(null);
                    }
                    if (PublicUtil.isNotEmpty(dmcDeviceAlertLifeRoomVo.getCreatedTime())) {
                        dmcDeviceAlertLifeRoomVo.setCreatedTime(dmcDeviceAlertLifeRoomVo.getCreatedTime().substring(0, dmcDeviceAlertLifeRoomVo.getCreatedTime().length() - 2));
                    }

                    if ((PublicUtil.isNotEmpty(dmcDeviceAlertLifeRoomVo.getUpdateTime()))) {
                        dmcDeviceAlertLifeRoomVo.setUpdateTime(dmcDeviceAlertLifeRoomVo.getUpdateTime().substring(0, dmcDeviceAlertLifeRoomVo.getUpdateTime().length() - 2));
                    }
                    //查看是否有报警视频
                    DmcCsunCameraAlertVideo dmcCsunCameraAlertVideo = videoService.selectByKey(dmcDeviceAlertLifeRoomVo.getAlertId());
                    if (PublicUtil.isNotEmpty(dmcCsunCameraAlertVideo)){
                        dmcDeviceAlertLifeRoomVo.setHaveVideos(true);
                    }

                }

            }
            return new PageInfo(dmcDeviceAlertLifeRoomVos);
        }
        return new PageInfo();
    }

    @Override
    public Integer updateAlerts(List<Long> alertIds, String loginName) {
        return dmcDeviceAlertMapper.updateAlerts(alertIds, loginName, new Date());
    }

    @Override
    public Long saveAlert(DmcDeviceAlert deviceAlertDto) {
        return dmcDeviceAlertMapper.saveAlert(deviceAlertDto);
    }

    @Override
    public int checkOldmanInRoomAndAlert(Integer roomId, Long groupId, Integer startDeviceType, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo) {
        //查询房间绑定的设备类型
        List<DmcDeviceByRoom> dmcDevices = dmcDeviceService.selectDeviceByRoomId(roomId.longValue(), groupId);
//        Map<Long, String> deviceMap = dmcDevices.stream().collect(Collectors.toMap(DmcDeviceByRoom::getDeviceType, DmcDeviceByRoom::getDeviceNo));

        /*
         * 2020-03-17 xcr
         * 人感设备处理
         * 一个房间绑定两个人感，编号为双数的人感决定在房状态
         * */
        /**
         * @date 2020-04-24
         * @author chisj
         * @desc 采用新人感检测老人是否在房
         */
//        Map<String, DmcDeviceByRoom> bodySensorMap = new HashMap<>();
//        dmcDevices.forEach(d -> {
//            if (d.getDeviceType() == DeviceConstant.NEWBODY) {
//                bodySensorMap.put(d.getDeviceNo(), d);
//            }
//        });
//        String bodysensorDeviceNo = "";
//        if (bodySensorMap.size() > 1) {
//            Set<String> bodysensorDeviceNoSet = bodySensorMap.keySet();
//            //双数人感上传是否在厕所消息
//            for (String b : bodysensorDeviceNoSet) {
//                String temp = b.substring(b.length() - 1);
//                if (Integer.parseInt(temp) % 2 == 0) {
//                    bodysensorDeviceNo = b;
//                }
//            }
//        }

        //将设备类型保存为map
        Map<Long, String> deviceMap = new HashMap<>();
        dmcDevices.forEach(d -> {
            deviceMap.put(d.getDeviceType(), d.getDeviceNo());
        });
        //将编号为双数的人感重新存储，刷新原来的value
//        if (!bodysensorDeviceNo.equals("")) {
//            deviceMap.put(DmcDeviceTypeEnum.CSUN_BODY_SENSOR.getIndex().longValue(), bodysensorDeviceNo);
//        }
        Set<Long> deviceTypeSet = deviceMap.keySet();

        //定义检测屋中是否有人的设备类型集合
        Set<Long> checkInRoomdeviceMap = Sets.newHashSet(DmcDeviceTypeEnum.NEWBODY.getIndex().longValue(),
                DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().longValue(),
                DmcDeviceTypeEnum.CSUN_CAMERA.getIndex().longValue()
        );

        //如果包含全部设备 检测各个设备的在房情况
        if (deviceTypeSet.containsAll(checkInRoomdeviceMap)) {
            //移除已经检测到无人的设备类型
            checkInRoomdeviceMap.remove(startDeviceType.longValue());
            int flag = 0;
            for (Long type : checkInRoomdeviceMap) {
                if (type.toString().equals(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().toString())) {
                    //查询床垫数据
                    CsunSleepData csunSleepData = (CsunSleepData) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunSleepKey(deviceMap.get(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().longValue())));
                    if (csunSleepData.getInBed() == 1 || csunSleepData.getStatus().equals(DeviceStatusEnum.OFFLINE.getKey())) {
                        log.info(" csun sleep offline or oldman is on bed. >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                } else if (type.toString().equals(DmcDeviceTypeEnum.NEWBODY.getIndex().toString())) {
                    //查询是否全部人感在线
//                    for (String k : bodySensorMap.keySet()) {
//                        if (!redisTemplate.hasKey(RedisKeyUtil.getCsunBodySensorOnline(k))) {
//                            log.info(" ==========================> bodysensor offline . >>>RoomId<<< => [{}]", roomId);
//                            return 0;
//                        }
//                    }
                    if (!redisTemplate.hasKey(RedisKeyUtil.getCsunBodySensorOnline(deviceMap.get(DmcDeviceTypeEnum.NEWBODY.getIndex().longValue())))) {
                        log.info(" ==========================> bodysensor offline . >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                    //查询人感数据
                    MsgBodysenorHome msgBodysenorHome = (MsgBodysenorHome) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunBodySensorIsInRoomKey(deviceMap.get(DmcDeviceTypeEnum.NEWBODY.getIndex().longValue())));
                    if (msgBodysenorHome != null && msgBodysenorHome.getHomeMsg().equals(LifeConstant.IN_ROOM_STATUS)) {
                        log.info(" gateway bound on bodysensor offline or sleep offline or oldman is in toilet. >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                } else if (type.toString().equals(DmcDeviceTypeEnum.CSUN_CAMERA.getIndex().toString())) {
                    //查询摄像头数据
                    CsunCameraData csunCameraData = (CsunCameraData) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunCameraKey(deviceMap.get(DmcDeviceTypeEnum.CSUN_CAMERA.getIndex().longValue())));
                    if (csunCameraData.getStatus().equals(DeviceStatusEnum.OFFLINE.getKey()) || csunCameraData.getHomeMsg().equals(LifeConstant.IN_ROOM_STATUS)) {
                        log.info(" camera offline or sleep or oldman is in camera vision. >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                }
                flag++;
            }
            if (flag == checkInRoomdeviceMap.size()) {

                //创建报警信息
//                DmcDeviceAlert dmcDeviceAlert = new DmcDeviceAlert();
//                OldmanBedRoomBuildingVo obrvo = new OldmanBedRoomBuildingVo();

                //查询配置的夜间报警时间
                LoginAuthDto loginAuthDto = new LoginAuthDto();
                loginAuthDto.setGroupId(groupId);
                LifeTransducerConfigVO configVO = dmcLifeTransducerRoomConfigService.getConfigByRoomId(roomId.longValue(), loginAuthDto);

                String leaveRoomAlertStartTime = configVO.getLeaveRoomAlertStartTime();
                String leaveRoomAlertEndTime = configVO.getLeaveRoomAlertEndTime();

                //未设置  不推送
                if (leaveRoomAlertStartTime == null || leaveRoomAlertEndTime == null) {
                    log.info(" Config has not value. >>>RoomId<<< => [{}]", roomId);
                    return 0;
                }

                //如果配置是00:00:00则不推送
                if (leaveRoomAlertStartTime.equals(LifeConstant.DEFAULT_LEAVE_ROOM_ALERT_START_TIME) &&
                        leaveRoomAlertEndTime.equals(LifeConstant.DEFAULT_LEAVE_ROOM_ALERT_END_TIME)) {
                    log.info(" default config do not need to alert. >>>RoomId<<< => [{}]", roomId);
                    return 0;
                }

                Date date = new Date();
                String todayStartTimeString = DateUtil.dateToStr(date) + " " + leaveRoomAlertStartTime;
                String todayEndTimeString = DateUtil.dateToStr(DateUtil.dateAdd(date, 1)) + " " + leaveRoomAlertEndTime;

                String yesterdayStartTimeString = DateUtil.dateToStr(DateUtil.dateAdd(date, -1)) + " " + leaveRoomAlertStartTime;
                String yesterdayEndTimeString = DateUtil.dateToStr(date) + " " + leaveRoomAlertEndTime;

                Date todayStartTime = DateUtil.strToDate(todayStartTimeString);
                Date todayEndTime = DateUtil.strToDate(todayEndTimeString);

                Date yesterdayStartTime = DateUtil.strToDate(yesterdayStartTimeString);
                Date yesterdayEndTime = DateUtil.strToDate(yesterdayEndTimeString);

                //如果在夜间报警范围内 发出推送
                if ((date.after(todayStartTime) && date.before(todayEndTime)) || (date.after(yesterdayStartTime) && date.before(yesterdayEndTime))) {
                    int result = csunSleepAlertMsg(deviceMap.get(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().longValue()), dmcDeviceAlert, obrvo, CsunSleepConstant.LEAVE_ROOM);
                    log.info("=====> dmcDeviceAlert = {}", dmcDeviceAlert.toString());
//                    if (result > 0)
//                        sendDeviceAlertMsg(dmcDeviceAlert, obrvo);
                    return result;
                }
            }
        } else {
            log.info(" the number of devices for checking in room is not enough. >>>RoomId<<< => [{}]", roomId);
        }
        return 0;
    }

    @Override
    public int checkOldmanInRoomAndAlert(Integer roomId, Long groupId, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo) {

        //查询房间绑定的设备类型
        List<DmcDeviceByRoom> dmcDevices = dmcDeviceService.selectDeviceByRoomId(roomId.longValue(), groupId);

        /*
         * 2020-03-17 xcr
         * 人感设备处理
         * 一个房间绑定两个人感，编号为双数的人感决定在房状态
         * */
//        Map<String, DmcDeviceByRoom> bodySensorMap = new HashMap<>();
//        dmcDevices.forEach(d -> {
//            if (d.getDeviceType() == DeviceConstant.CSUN_BODY_SENSOR) {
//                bodySensorMap.put(d.getDeviceNo(), d);
//            }
//        });
//        String bodysensorDeviceNo = "";
//        if (bodySensorMap.size() > 1) {
//            Set<String> bodysensorDeviceNoSet = bodySensorMap.keySet();
//            //双数人感上传是否在厕所消息
//            for (String b : bodysensorDeviceNoSet) {
//                String temp = b.substring(b.length() - 1);
//                if (Integer.parseInt(temp) % 2 == 0) {
//                    bodysensorDeviceNo = b;
//                }
//            }
//        }

        //将设备类型保存为map
        Map<Long, String> deviceMap = new HashMap<>();
        dmcDevices.forEach(d -> {
            deviceMap.put(d.getDeviceType(), d.getDeviceNo());
        });
        //将编号为双数的人感重新存储，刷新原来的value
//        if (!bodysensorDeviceNo.equals("")) {
//            deviceMap.put(DmcDeviceTypeEnum.CSUN_BODY_SENSOR.getIndex().longValue(), bodysensorDeviceNo);
//        }
        Set<Long> deviceTypeSet = deviceMap.keySet();

        //定义检测屋中是否有人的设备类型集合
        Set<Long> checkInRoomdeviceMap = Sets.newHashSet(DmcDeviceTypeEnum.NEWBODY.getIndex().longValue(),
                DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().longValue(),
                DmcDeviceTypeEnum.CSUN_CAMERA.getIndex().longValue()
        );

        //如果包含全部设备 检测各个设备的在房情况
        if (deviceTypeSet.containsAll(checkInRoomdeviceMap)) {

            int flag = 0;
            for (Long type : checkInRoomdeviceMap) {
                if (type.toString().equals(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().toString())) {
                    //查询床垫数据
                    CsunSleepData csunSleepData = (CsunSleepData) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunSleepKey(deviceMap.get(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().longValue())));
                    if (csunSleepData.getInBed() == 1 || csunSleepData.getStatus().equals(DeviceStatusEnum.OFFLINE.getKey())) {
                        log.info(" csun sleep offline or oldman is on bed. >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                } else if (type.toString().equals(DmcDeviceTypeEnum.NEWBODY.getIndex().toString())) {
                    //查询是否全部人感在线
//                    for (String k : bodySensorMap.keySet()) {
//                        if (!redisTemplate.hasKey(RedisKeyUtil.getCsunBodySensorOnline(k))) {
//                            log.info(" ==========================> bodysensor offline . >>>RoomId<<< => [{}]", roomId);
//                            return 0;
//                        }
//                    }
                    if (!redisTemplate.hasKey(RedisKeyUtil.getCsunBodySensorOnline(deviceMap.get(DmcDeviceTypeEnum.NEWBODY.getIndex().longValue())))) {
                        log.info(" ==========================> bodysensor offline . >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                    //查询人感数据
                    MsgBodysenorHome msgBodysenorHome = (MsgBodysenorHome) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunBodySensorIsInRoomKey(deviceMap.get(DmcDeviceTypeEnum.NEWBODY.getIndex().longValue())));
                    if (msgBodysenorHome != null && msgBodysenorHome.getHomeMsg().equals(LifeConstant.IN_ROOM_STATUS)) {
                        log.info(" gateway bound on bodysensor offline or sleep offline or oldman is in toilet. >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                } else if (type.toString().equals(DmcDeviceTypeEnum.CSUN_CAMERA.getIndex().toString())) {
                    //查询摄像头数据
                    CsunCameraData csunCameraData = (CsunCameraData) redisTemplate.opsForValue().get(RedisKeyUtil.getCsunCameraKey(deviceMap.get(DmcDeviceTypeEnum.CSUN_CAMERA.getIndex().longValue())));
                    if (csunCameraData.getStatus().equals(DeviceStatusEnum.OFFLINE.getKey()) || csunCameraData.getHomeMsg().equals(LifeConstant.IN_ROOM_STATUS)) {
                        log.info(" camera offline or sleep or oldman is in camera vision. >>>RoomId<<< => [{}]", roomId);
                        return 0;
                    }
                }
                flag++;
            }
            if (flag == checkInRoomdeviceMap.size()) {

                //创建报警信息
//                DmcDeviceAlert dmcDeviceAlert = new DmcDeviceAlert();
//                OldmanBedRoomBuildingVo obrvo = new OldmanBedRoomBuildingVo();

                //推送报警
                int result = csunSleepAlertMsg(deviceMap.get(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex().longValue()), dmcDeviceAlert, obrvo, CsunSleepConstant.LEAVE_ROOM);
                log.info("=====> dmcDeviceAlert = {}", dmcDeviceAlert.toString());
//                if (result > 0)
//                    sendDeviceAlertMsg(dmcDeviceAlert, obrvo);
                return result;
            }
        } else {
            log.info(" the number of devices for checking in room is not enough. >>>RoomId<<< => [{}]", roomId);
        }
        return 0;
    }

    @Override
    public int deviceOfflineAlert(String deviceNo, DmcDeviceAlert dmcDeviceAlert, OldmanBedRoomBuildingVo obrvo) {

        //定义标志，决定是否需要报警
        int flag = 0;

        //查询设备信息
        DmcDevice dmcDevice = dmcDeviceService.queryDeviceByNumber(deviceNo);
        Long groupId = dmcDevice.getGroupId();
        Integer deviceType = dmcDevice.getDeviceType();
        String alertCode = "";

        switch (deviceType) {
            case DeviceConstant.CSUN_CAMERA:
                alertCode = AlertConfigConstant.CAMERA_OFFLINE_ALERT_CODE;
                break;
            case DeviceConstant.CSUN_SLEEP:
                alertCode = AlertConfigConstant.CSUNSLEEP_OFFLINE_ALERT_CODE;
                break;
            case DeviceConstant.CSUN_GATEWAY:
                alertCode = AlertConfigConstant.GATEWAY_OFFLINE_ALERT_CODE;
                break;
            case DeviceConstant.CSUN_BODY_SENSOR:
                alertCode = AlertConfigConstant.BODYSENSOR_OFFLINE_ALERT_CODE;
                break;
            case DeviceConstant.NEWBODY:
                alertCode = AlertConfigConstant.BODYSENSOR_OFFLINE_ALERT_CODE;
                break;
            case DeviceConstant.HUMIDISTAT:
                alertCode = AlertConfigConstant.HUMIDISTAT_OFFLINE_ALERT_CODE;
                break;
            default:
                log.info("No offline alert device => [{}]", deviceNo);
                return flag;
        }

        //插入离线报警日志
        Integer save = dmcDeviceOnlineRecordService.insertRecordByDeviceNo(deviceNo, OnlineConstant.OFF_LINE);
        if (save > 0) {
            log.info(deviceNo, "插入离线日志成功");
        }

        //查看系统缓存  是否配置了离线报警
        Set<String> codeSet = groupOfflineAlertConfigMap.get(groupId);

        //当系统缓存无该机构报警配置
        if (codeSet == null) {
            //查询机构报警
            AlertConfigQueryDto queryDto = new AlertConfigQueryDto();
            queryDto.setGroupId(dmcDevice.getGroupId());
            queryDto.setStatus(AlertConfigConstant.ALERT_ON);
            List<ConfigureOfflineAlertGroupVO> configList = dmcConfigureOfflineAlertGroupService.list(queryDto);
            Set<String> configSet = configList.stream().map(c -> c.getAlertCode()).collect(Collectors.toSet());

            //如果需要报警，将flag置为1
            if (configSet.contains(alertCode)) {
                flag = 1;
            }
            //将机构报警配置存入系统缓存
            if (configSet.size() > 0) {
                groupOfflineAlertConfigMap.put(groupId, configSet);
            }

            //如果系统缓存有数据 查询是否配置了报警
        } else if (codeSet.contains(alertCode)) {
            //配置了报警 则将flag置为1
            flag = 1;
        }

        int result = 0;
        //如果flag为1则推送报警
        if (flag == 1) {

            switch (deviceType) {
                case DeviceConstant.CSUN_CAMERA:
                    result = csunCameraAlertMsg(dmcDevice.getId(), dmcDeviceAlert, obrvo, CameraConstant.OFF_LINE);
                    break;
                case DeviceConstant.CSUN_SLEEP:
                    result = csunSleepAlertMsg(dmcDevice.getDeviceNo(), dmcDeviceAlert, obrvo, CsunSleepConstant.OFF_LINE);
                    SleepMessageHandler.expireRedisKeySet.remove(RedisKeyUtil.getCsunSleepOnline(deviceNo));
                    redisTemplate.delete(RedisKeyUtil.getCsunSleepOnline(deviceNo));
                    break;
                case DeviceConstant.CSUN_BODY_SENSOR:
                    result = csunBodySensorAlertMsg(dmcDevice.getDeviceNo(), dmcDeviceAlert, obrvo, BodySensorConstant.OFF_LINE);
                    SleepMessageHandler.expireRedisKeySet.remove(RedisKeyUtil.getCsunBodySensorOnline(deviceNo));
                    redisTemplate.delete(RedisKeyUtil.getCsunBodySensorOnline(deviceNo));
                    break;
                case DeviceConstant.NEWBODY:
                    result = csunBodySensorAlertMsg(dmcDevice.getDeviceNo(), dmcDeviceAlert, obrvo, BodySensorConstant.OFF_LINE);
                    SleepMessageHandler.expireRedisKeySet.remove(RedisKeyUtil.getCsunBodySensorOnline(deviceNo));
                    redisTemplate.delete(RedisKeyUtil.getCsunBodySensorOnline(deviceNo));
                    break;
                case DeviceConstant.CSUN_GATEWAY:
                    result = csunGatewayAlertMsg(dmcDevice.getDeviceNo(), dmcDeviceAlert, obrvo, GatewayConstant.OFF_LINE);
                    SleepMessageHandler.expireRedisKeySet.remove(RedisKeyUtil.getCsunGatewayOnline(deviceNo));
                    redisTemplate.delete(RedisKeyUtil.getCsunGatewayOnline(deviceNo));
                    break;
                case DeviceConstant.HUMIDISTAT:
                    result = csunHumidistatAlertMsg(dmcDevice.getDeviceNo(), dmcDeviceAlert, obrvo, HumidistatConstant.OFF_LINE);
                    SleepMessageHandler.expireRedisKeySet.remove(RedisKeyUtil.getCsunHumidistatOnline(deviceNo));
                    redisTemplate.delete(RedisKeyUtil.getCsunHumidistatOnline(deviceNo));
                    break;
            }
            log.info("=====> dmcDeviceAlert = {}", dmcDeviceAlert.toString());
//            if (result > 0) {
//                sendDeviceAlertMsg(dmcDeviceAlert, obrvo);
//            }
        }
        return result;
    }

    @Override
    public List<DmcDeviceAlertLifeVo> queryDeviceAlertLifeByIos(DeviceAlertLifeByIosSelectDto deviceAlertLifeByIosSelectDto) {
        List<DmcDeviceAlertLifeVo> dmcDeviceAlertLifeVos = dmcDeviceAlertMapper.queryDeviceAlertLifeByIos(deviceAlertLifeByIosSelectDto);
        return dmcDeviceAlertLifeVos;
    }
    //查询该设备最新报警时间
    @Override
    public List<DmcDeviceAlertVo> queryDeviceAlert(DeviceAlertPageQuery deviceAlertPageQuery) {
        return dmcDeviceAlertMapper.queryDeviceAlert(deviceAlertPageQuery);
    }
    /**
     * 守护佳床垫报警按时间分布
     * @return Wrapper
     */
    @Override
    public SleepAlertByHour selectSleepAlertByhour(Long groupId) {
        return dmcDeviceAlertMapper.selectSleepAlertByhour(groupId);
    }
    //查询床垫报警
    @Override
    public List<com.csun.cmny.provider.model.vo.DmcDeviceAlert> queryDeviceAlertBySleep(List<DmcCsunSleepVo> dmcCsunSleepVos) {
        return dmcDeviceAlertMapper.queryDeviceAlertBySleep(dmcCsunSleepVos);
    }

    public boolean getRoomOldmanCheckStat(Integer roomId) {

        OldmanCheckStatDto oldmanCheckStatDto = (OldmanCheckStatDto) redisTemplate.opsForValue()
                .get(RedisKeyUtil.getOmcRoomCheckStat(roomId.longValue()));
        if (PublicUtil.isNotEmpty(oldmanCheckStatDto)) {
            // 如果从1(入居中) --> 2(一时外出中) 不产生新的报警, 可以查出老的报警记录
            // 如果从2(一时外出中) --> 1(入居中) 可以产生报警
            if (oldmanCheckStatDto.getCheckStat().equals(2)) {
                return true;
            }
        }

        return false;
    }
}
